import argparse
import datetime
import os
import time
import zipfile

from Constants import TEST_TIME
from Constants import realAppList
from Constants import demoAppList


def parse_args():
    # 解析输入参数
    parser = argparse.ArgumentParser(
        description='Tools for analyse battery consume',
    )
    parser.add_argument('--deviceIP')
    parser.add_argument('--testTime', default=3)
    """
        origin    :原生策略
        fullAlign :全对齐策略
        fullAlign     :对齐不延迟策略
        simpty    :对比论文策略
        standalone:排除standalone策略
    """
    parser.add_argument('--policy', default="origin", choices=['origin','fullAlign','fullAlign','simpty','fullAlign'])
    parser.add_argument('--out_path', default="../batteryStats/DumpBatteryStats")
    parser.add_argument('--tmp_unzip_path',default="batteryStats/DumpBatteryStats/Tmp/Unzip")
    parser.add_argument('--lunchAPP',default="real",choices=['realAPP','demoAPP'])
    args = parser.parse_args()
    return args

# 唤醒appList中的应用，每个应用等待7秒
def lunchApp(deviceIP,lunchList):
    print("******** rebooting ******* \n")
    os.system('adb -s {} reboot'.format(deviceIP))
    time.sleep(2 * 60)

    # 连接设备
    os.system("adb connect {}".format(deviceIP))

    # 唤醒屏幕
    os.system("adb -s {} shell input keyevent 224".format(deviceIP))
    # 上滑解锁
    os.system("adb -s {}  shell input swipe 300 1000 300 200".format(deviceIP))

    for app in lunchList:
        print("******** lunchApp %s *******" % app)
        os.system("adb -s {} shell monkey -p {} -v 1".format(deviceIP, app))
        time.sleep(4)
    os.system('adb -s {} shell dumpsys batterystats --reset'.format(deviceIP))

    time.sleep(2)
    # 休眠
    os.system("adb -s {} shell input keyevent 26".format(deviceIP))


# 测试完成后的收集操作
def collectionData(deviceIP, savePath):
    time.sleep(TEST_TIME)

    day = datetime.datetime.now()
    fileName = "{}_{}_{}_{}_{}.zip".format(deviceIP,day.month,day.day,day.hour,day.minute)
    filePath = os.path.join(savePath, fileName)
    # 唤醒屏幕
    os.system("adb -s {} shell input keyevent 224".format(deviceIP))

    print("******** dump Battery *******")
    os.system('adb -s {} bugreport {}'.format(deviceIP,filePath))

    # TODO: 解压bugreport文件到tmp文件中，并将其中的文件移至测试目录下，异步执行该操作，不要堵塞主线程

def unzipBattery(fileName):
    zipFile = zipfile.ZipFile(fileName)
    zipFile.extract()

# 刷入对应的包
def flashJar():
    # TODO: 刷入不同版本的包
    pass

if __name__ == '__main__':
    args = parse_args()
    deviceIP = args.deviceIP
    testTimes = args.testTime
    savePath = args.out_path
    policy = args.policy
    lunchAPP = args.lunchAPP

    lunchList = realAppList if lunchAPP == "realAPP" else demoAppList
    savePath = os.path.join(savePath,lunchAPP,policy)
    # 判断是否存在对应的文件目录
    if not os.path.exists(savePath):
        os.makedirs(savePath)

    for i in range(testTimes):
        lunchApp(deviceIP,lunchList)
        print("******** testing *******")
        collectionData(deviceIP,savePath)
